package com.bzgwl.cloud_gateway.filter;

import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Professor_Kong
 * @version 1.0
 * @date 2020/3/31 16:28
 */
@Component
@SuppressWarnings("all")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain filterChain) throws IOException, ServletException {
        RequestContext ctx = RequestContext.getCurrentContext();


        HttpServletRequest request =(HttpServletRequest)request1;
        HttpServletResponse response = (HttpServletResponse)response1;
        String header = request.getHeader("Authorization");
        String headerToken = request.getHeader("token");



        StringBuffer requestURI = request.getRequestURL();
        String token = request.getParameter("token");
        if(StringUtils.isNotBlank(token)){
            try {
                HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);

                //如果请求中带有这个参数，则进行过滤加一个header头
                requestWrapper.addHeader("Authorization", token);
                requestWrapper.addHeader("token", token);

                filterChain.doFilter(requestWrapper, response);

            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            filterChain.doFilter(request,response);
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
